// Author: wsfuyibing <682805@qq.com>
// Date: 2025-07-04

package close

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/log"
	"server/app/http/models"
	"server/app/kind"
	"server/app/lib/order/operations"
	"sync"
)

var (
	once     = new(sync.Once)
	operator *Operator
)

// Operator
// 关闭订单.
type Operator struct {
	operations.Operations
}

// New
// 操作单例.
func New() *Operator { return operator }

// Run
// 执行创建.
func (o *Operator) Run(ctx context.Context, sess *db.Session, order *models.Order, by kind.ClosedBy) (err error) {
	// 1. 开始关闭.
	log.Infofc(ctx, `[lib][order] 开始关闭`)

	// 2. 监听结束.
	defer func() {
		if err != nil {
			log.Warnfc(ctx, `[lib][order] 关闭失败: %v`, err)
		} else {
			order.State = kind.OrderStateClosed
			log.Infofc(ctx, `[lib][order] 关闭结束`)
		}
	}()

	// 3. 关闭订单.
	if err = o.UpdateStateAsClosed(ctx, sess, order, kind.OrderOperationClosed, by, kind.LinkDetailOrder, kind.LinkParams{
		"Id":      order.Id,
		"OrderNo": order.OrderNo,
	}); err != nil {
		return
	}

	// 4. 解冻库存.
	err = o.Unlock(ctx, sess, order)
	return
}

// +---------------------------------------------------------------------------+
// | Initialize a singleton instance.                                          |
// +---------------------------------------------------------------------------+

func init() {
	once.Do(func() {
		operator = &Operator{}
	})
}
